﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.FoundationModel;
using MINERP.DAL;
using MINERP.COM;
using System.Data;
using MINERP.DAL.Statistics;
using MINERP.DAL.CommonDAL;

namespace MINERP.BLL.Statistics
{
    public class NewPerformanceBLL
    {
        /// <summary>
        /// 获取用户某时间段内的业绩，开单时间、提交时间排序
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <param name="curUserId"></param>
        /// <returns></returns>
        public List<NewPerformanceInfo> GetOnePerfromance(DateTime dtStart, DateTime dtEnd, int curUserId)
        {
            string curUserName = "用户已删除";
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                users curU = db.users.FirstOrDefault(u => u.userID == curUserId);
                if (curU != null)
                {
                    curUserName = curU.UserName;
                }
                else
                {
                    return null;
                }
                List<New_EmployeePerformance> listSource = db.New_EmployeePerformance.Where(e => e.TechCompletedTime <= dtEnd && e.TechCompletedTime >= dtStart && e.UserId == curUserId).ToList();

                return ConvertEmployeePerformanceToInfo(listSource, curUserName, db);
            }
        }

        private List<NewPerformanceInfo> ConvertEmployeePerformanceToInfo(List<New_EmployeePerformance> soruceList, string curUserName, newSampleYPDBEntities db)
        {
            List<NewPerformanceInfo> result = new List<NewPerformanceInfo>();
            foreach (var e in soruceList)
            {
                result.Add(new NewPerformanceInfo()
                {
                    CtmName = e.CtmName,
                    MultiplePageNum = e.MultiplePageNum,
                    OrderArea = e.Status==(int)OrderInfoStatus.Completed?Math.Round(e.OrderArea,4):0,
                    OrderCompletedTime = e.OrderConpletedTime ?? DateTime.Now,
                    OrderCount = Math.Round(e.OrderCount,2),
                    OrderCreateTime = e.OrderCreateTime,
                    OrderPath = e.OrderPath,
                    OrderProductId = e.OrderproductId,
                    OrderProductName = e.OrderProductName,
                    PhotoTotalNum = e.PhotoTotalNum,
                    PreOrderArea = Math.Round(e.PreOrderAreas,4),
                    ReceivedTime = e.ReceivedTime,
                    ShopName = e.ShopName,
                    SinglePageNum = e.SinglePageNum,
                    Status = e.Status,
                    TechCompletedTime = e.TechCompletedTime,
                    TechId = e.TechId,
                    UserName = curUserName,
                    TechName = db.tb_Tech.FirstOrDefault(t => t.TechId == e.TechId).TechName,
                    ProductPhotoNum=e.ProductPhotoNum
                });
            }

            return result;
        }

        /// <summary>
        /// 当进行产品的删除(包括在客服界面的删除、还有在编辑界面的删除)、暂停、恢复时调用此方法
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <param name="status">就是orderInfo的状态</param>
        public static void SetPerformanceStatus(int orderProductId, OrderInfoStatus status)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var em in db.New_EmployeePerformance.Where(e => e.OrderproductId == orderProductId).ToList())
                {
                    em.Status = (int)status;
                }

                db.SaveChanges();
            }
        }

        public List<UserInfo> GetUserListByGroupId(int GroupId)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                if (GroupId == 0)
                {
                    return ConvertUserToInfo(db.users.Where(u=>u.IsUseful==true).ToList());
                }
                else
                {
                    return ConvertUserToInfo(db.users.Where(u => u.tb_WorkerGroup.GroupId == GroupId&&u.IsUseful==true).ToList());
                }
            }
        }

        private List<UserInfo> ConvertUserToInfo(List<users> uList)
        {
            List<UserInfo> result = new List<UserInfo>();

            foreach (var u in uList)
            {
                result.Add(new UserInfo()
                {
                    UserID = u.userID,
                    UserName = u.UserName

                });
            }

            return result;
        }

        public List<NewPerformanceInfo> GetOnePerfromance(DateTime startDT, DateTime endDT, List<int> selectedUserIDList)
        {
            List<NewPerformanceInfo> result = new List<NewPerformanceInfo>();
            foreach (var uid in selectedUserIDList)
            {
                result.AddRange(GetOnePerfromance(startDT, endDT, uid));
            }

            return result;
        }

        public DataTable GetPerfromances(DateTime startDT, DateTime endDT, List<int> selectedUserIDList)
        {
            string users="";
            selectedUserIDList.ForEach(delegate(int user){
            users+=user+",";});
            users=users.TrimEnd(',');
            string SQL = "select  OrderproductId, TechName, ShopName, CtmName, OrderProductName" +    //,   CASE CHARINDEX('_',ORDERPRODUCTNAME) WHEN 0 THEN ORDERPRODUCTNAME ELSE "+
              //           "(case OrderProductName when ' ' then ' ' else REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName), CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) end) END  AS ProductName" +
                         ",CASE CHARINDEX('_',ORDERPRODUCTNAME) WHEN 0 THEN ORDERPRODUCTNAME ELSE (case OrderProductName when ' ' then ' ' else REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName), CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) end) END  AS ProductName,OrderCreateTime,ReceivedTime, UserName,case Status when 7 then '暂停' when 12 then '已删除'  when 8 then '已完成 ' else  '正常生产' end  as StatusName , PhotoTotalNum, SinglePageNum, " +
                         " MultiplePageNum, OrderPath, TechCompletedTime, OrderConpletedTime, PreOrderAreas, OrderArea, OrderCount, ProductPhotoNum " +
                         " from New_EmployeePerformance,users,tb_Tech " +
                         " where New_EmployeePerformance.TechId=tb_Tech.TechId and users.userid=New_EmployeePerformance.userid " +
                         " and New_EmployeePerformance.userid in (" + users + ") and TechCompletedTime<'" + endDT.ToString() + "'and  TechCompletedTime>'" + startDT.ToString() + "'";
           return  CommOperDB.ExceSQLDataTable(SQL);
        }
        public DataTable GetPerfromancesBK(DateTime startDT, DateTime endDT, List<int> selectedUserIDList)
        {
            string users = "";
            selectedUserIDList.ForEach(delegate(int user)
            {
                users += user + ",";
            });
            users = users.TrimEnd(',');
            string SQL = "select  OrderproductId, TechName, ShopName, CtmName, OrderProductName" +    //,   CASE CHARINDEX('_',ORDERPRODUCTNAME) WHEN 0 THEN ORDERPRODUCTNAME ELSE "+
                //           "(case OrderProductName when ' ' then ' ' else REVERSE(LEFT(REVERSE(New_EmployeePerformance_BK.OrderProductName), CHARINDEX('_', REVERSE(New_EmployeePerformance_BK.OrderProductName)) - 1)) end) END  AS ProductName" +
                        ",CASE CHARINDEX('_',ORDERPRODUCTNAME) WHEN 0 THEN ORDERPRODUCTNAME ELSE (case OrderProductName when ' ' then ' ' else REVERSE(LEFT(REVERSE(New_EmployeePerformance_BK.OrderProductName), CHARINDEX('_', REVERSE(New_EmployeePerformance_BK.OrderProductName)) - 1)) end) END  AS ProductName,OrderCreateTime,ReceivedTime, UserName,case Status when 7 then '暂停' when 12 then '已删除'  when 8 then '已完成 ' else  '正常生产' end  as StatusName , PhotoTotalNum, SinglePageNum, " +
                        " MultiplePageNum, OrderPath, TechCompletedTime, OrderConpletedTime, PreOrderAreas, OrderArea, OrderCount, ProductPhotoNum " +
                        " from New_EmployeePerformance_BK,users,tb_Tech " +
                        " where New_EmployeePerformance_BK.TechId=tb_Tech.TechId and users.userid=New_EmployeePerformance_BK.userid " +
                        " and New_EmployeePerformance_BK.userid in (" + users + ") and TechCompletedTime<'" + endDT.ToString() + "'and  TechCompletedTime>'" + startDT.ToString() + "'";
            return CommOperDB.ExceSQLDataTable(SQL);
        }
        public DataTable GetHistoryFilter(int userId, DateTime startTime, DateTime endTime)
        {
            string sql = " SELECT     New_EmployeePerformance.OrderproductId, tb_Tech.TechName, New_EmployeePerformance.ShopName, New_EmployeePerformance.CtmName, " +
                       " New_EmployeePerformance.OrderProductName, CASE CHARINDEX('_', ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, CASE CHARINDEX('_', " +
                       " ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, " +
                      " New_EmployeePerformance.OrderCreateTime, New_EmployeePerformance.ReceivedTime, users.UserName, " +
                      " CASE Status WHEN 7 THEN '暂停' WHEN 12 THEN '已删除' WHEN 8 THEN '已完成 ' ELSE '正常生产' END AS StatusName, " +
                      " New_EmployeePerformance.PhotoTotalNum, New_EmployeePerformance.SinglePageNum, New_EmployeePerformance.MultiplePageNum, " +
                      " New_EmployeePerformance.OrderPath, New_EmployeePerformance.TechCompletedTime, New_EmployeePerformance.OrderConpletedTime, " +
                      " New_EmployeePerformance.PreOrderAreas, New_EmployeePerformance.OrderArea, New_EmployeePerformance.OrderCount, " +
                      " New_EmployeePerformance.ProductPhotoNum" +
" FROM         New_EmployeePerformance INNER JOIN" +
                      " tb_Tech ON New_EmployeePerformance.TechId = tb_Tech.TechId INNER JOIN" +
                      " users ON New_EmployeePerformance.UserId = users.userID" +
" WHERE     (New_EmployeePerformance.UserId =" + userId + ") AND (New_EmployeePerformance.TechCompletedTime < '" + endTime.ToString() + "') AND " +
                      " (New_EmployeePerformance.TechCompletedTime > '" + startTime.ToString() + "')";

            return CommOperDB.ExceSQLDataTable(sql);

        }

        public DataTable GetHistoryFilterAll(int userId, DateTime startTime, DateTime endTime)
        {
            string sql = " SELECT     New_EmployeePerformance.OrderproductId, tb_Tech.TechName, New_EmployeePerformance.ShopName, New_EmployeePerformance.CtmName, " +
                       " New_EmployeePerformance.OrderProductName, CASE CHARINDEX('_', ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, CASE CHARINDEX('_', " +
                       " ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, " +
                      " New_EmployeePerformance.OrderCreateTime, New_EmployeePerformance.ReceivedTime, users.UserName, " +
                      " CASE Status WHEN 7 THEN '暂停' WHEN 12 THEN '已删除' WHEN 8 THEN '已完成 ' ELSE '正常生产' END AS StatusName, " +
                      " New_EmployeePerformance.PhotoTotalNum, New_EmployeePerformance.SinglePageNum, New_EmployeePerformance.MultiplePageNum, " +
                      " New_EmployeePerformance.OrderPath, New_EmployeePerformance.TechCompletedTime, New_EmployeePerformance.OrderConpletedTime, " +
                      " New_EmployeePerformance.PreOrderAreas, New_EmployeePerformance.OrderArea, New_EmployeePerformance.OrderCount, " +
                      " New_EmployeePerformance.ProductPhotoNum" +
" FROM         New_EmployeePerformance INNER JOIN" +
                      " tb_Tech ON New_EmployeePerformance.TechId = tb_Tech.TechId INNER JOIN" +
                      " users ON New_EmployeePerformance.UserId = users.userID" +
" WHERE     (New_EmployeePerformance.UserId in (select userid from users where GroupId = (select GroupId from users where userid=" + userId + " ) and IsUseful=1)) AND (New_EmployeePerformance.TechCompletedTime < '" + endTime.ToString() + "') AND " +
                      " (New_EmployeePerformance.TechCompletedTime > '" + startTime.ToString() + "')";

            return CommOperDB.ExceSQLDataTable(sql);

        }
        public DataTable GetDeliverStat(List<int> inUserID, DateTime inStartDate, DateTime inEndDate)
        {
            PerformanceDAL _PDAL=new PerformanceDAL();
            return _PDAL.GetDeliverStat(inUserID, inStartDate, inEndDate);


        }


    }
}
